#!/usr/bin/env node

/**
 * 快速检查admin表关联状态
 */

const AdminModel = require('./model/admin_model.js');

async function quickCheckAdmin() {
    try {
        console.log('=== 快速检查admin表关联状态 ===');
        
        const userId = 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 微信openId
        
        console.log('检查用户ID:', userId);
        
        // 查询所有admin记录
        const allAdmins = await AdminModel.getList({}, 'ADMIN_ID,ADMIN_NAME,linkedUserId,ADMIN_STATUS,isActive');
        
        console.log('\n所有admin记录:');
        allAdmins.forEach((admin, index) => {
            console.log(`${index + 1}. Admin ID: ${admin.ADMIN_ID}`);
            console.log(`   Admin Name: ${admin.ADMIN_NAME}`);
            console.log(`   Linked User ID: ${admin.linkedUserId || '未关联'}`);
            console.log(`   Admin Status: ${admin.ADMIN_STATUS}`);
            console.log(`   Is Active: ${admin.isActive}`);
            console.log(`   是否匹配当前用户: ${admin.linkedUserId === userId ? '✅ 是' : '❌ 否'}`);
            console.log('---');
        });
        
        // 查询当前用户关联的admin
        const userAdmin = await AdminModel.getOne({
            linkedUserId: userId,
            ADMIN_STATUS: 1,
            isActive: true
        }, 'ADMIN_ID,ADMIN_NAME,ADMIN_TYPE,linkedStoreIds,permissions,role');
        
        if (userAdmin) {
            console.log('\n✅ 找到关联的admin账号:');
            console.log('Admin ID:', userAdmin.ADMIN_ID);
            console.log('Admin Name:', userAdmin.ADMIN_NAME);
            console.log('Admin Type:', userAdmin.ADMIN_TYPE);
            console.log('Role:', userAdmin.role);
            console.log('Permissions:', userAdmin.permissions);
            console.log('Linked Store IDs:', userAdmin.linkedStoreIds);
        } else {
            console.log('\n❌ 未找到关联的admin账号');
            console.log('可能的原因:');
            console.log('1. admin表中没有linkedUserId为', userId, '的记录');
            console.log('2. admin记录的ADMIN_STATUS不为1');
            console.log('3. admin记录的isActive不为true');
        }
        
        console.log('\n=== 检查完成 ===');
        
        return {
            success: true,
            hasAdmin: !!userAdmin,
            admin: userAdmin,
            allAdmins: allAdmins
        };
        
    } catch (error) {
        console.error('❌ 检查失败:', error);
        return {
            success: false,
            message: '检查失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    quickCheckAdmin().then(result => {
        console.log('检查结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { quickCheckAdmin };
